import setting from "@/setting.js";
import {ElMessage} from "element-plus";

export default {


};

export async function refreshAndRetry() {
    try {
        const accessToken=localStorage.getItem('access_token');
        const refreshToken = localStorage.getItem('refresh_token'); // ... 其他
        const refreshResponse = await fetch(`${setting.API_URL}/user/refresh/`, {
            method: 'POST', headers: {
                'Content-Type': 'application/json'
            }, body: JSON.stringify({refresh:refreshToken})
        });

        if (!refreshResponse.ok) {
            ElMessage({
                type: 'error', message: '刷新失败，请重新登录'
            });
            // 跳转到登录页面
            window.location.href = '/login';

        }

        const refreshedData = await refreshResponse.json();
        localStorage.setItem('access_token', refreshedData.access);
        return true;

    } catch (error) {
        if (error.message.includes('401')) {
            window.location.href = '/login';
        } else {
            throw error;
        }
        return false;
    }
    return false;
}

export async function jsonApi(api_url, json_body='',is_access=true) {
    try {
        const accessToken=localStorage.getItem('access_token');
        const refreshToken = localStorage.getItem('refresh_token'); // ... 其他
        let headers;
        if(!is_access){
            headers ={
                'Content-Type': 'application/json' // 指定发送的内容类型为JSON
            }
        }else{
            headers ={
                'Authorization': `Bearer ${accessToken}`,
                'Content-Type': 'application/json' // 指定发送的内容类型为JSON
            }
        }
        const response = await fetch(setting.API_URL+api_url, {
            method: 'POST', // 如果API是要求POST请求的话
            headers: headers, body: json_body // 将请求体对象转换为JSON字符串
        });
        if (!response.ok) {
            if (response.status === 401 && is_access===true) {
                //读取
                /*
                * {
                    "detail": "此令牌对任何类型的令牌无效",
                    "code": "token_not_valid",
                    "messages": [
                    {
                         "token_class": "AccessToken",
                         "token_type": "access",
                         "message": "令牌类型错误"
                     }
                     ]
                }*/
                // 判断code字段是否如此

                const responseData = await response.json();
                if (responseData.code === 'token_not_valid') {
                    // 刷新token
                    const refreshSuccess = await refreshAndRetry();
                    if (refreshSuccess) {
                        // 刷新成功，重新发送请求
                        return await jsonApi(api_url, json_body);
                    }
                }
            }
            return response;
        }else{
            return response;
        }
    } catch (error) {
        ElMessage({data: error,
            type: 'error', message: 'api请求失败,请检查网络 :'+error
        });
    }


}

export async function formDataApi(api_url, formData) {
    try {
        const accessToken = localStorage.getItem('access_token');
        const refreshToken = localStorage.getItem('refresh_token'); // ... 其他
        const response = await fetch(setting.API_URL+api_url, {
            method: 'POST', body: formData, headers: {
                'Authorization': `Bearer ${accessToken}`,
            },
        });
        if (!response.ok) {
            if (response.status === 401) {
                //读取
                /*
                * {
                    "detail": "此令牌对任何类型的令牌无效",
                    "code": "token_not_valid",
                    "messages": [
                    {
                         "token_class": "AccessToken",
                         "token_type": "access",
                         "message": "令牌类型错误"
                     }
                     ]
                }*/
                // 判断code字段是否如此

                const responseData = await response.json();
                if (responseData.code === 'token_not_valid') {
                    // 刷新token
                    const refreshSuccess = await refreshAndRetry();
                    if (refreshSuccess) {
                        // 刷新成功，重新发送请求
                        return await formDataApi(api_url, formData);
                    }
                }
            }
            return response;
        } else {
            return response;
        }
    } catch (error) {
        ElMessage({
            data: error, type: 'error', message: 'api请求失败:' + error
        });
    }

}
